package com.houweishi.module.copy.controller;

import cn.hutool.core.util.StrUtil;
import com.houweishi.common.annotation.Excel;
import com.houweishi.common.annotation.Log;
import com.houweishi.common.core.controller.BaseController;
import com.houweishi.common.core.domain.AjaxResult;
import com.houweishi.common.core.page.TableDataInfo;
import com.houweishi.common.enums.BusinessType;
import com.houweishi.common.utils.poi.ExcelUtil;
import com.houweishi.module.copy.domain.BizCopy;
import com.houweishi.module.copy.service.IBizCopyService;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.List;

/**
 * 审批抄送管理Controller
 *
 * @author houweishi
 * @date 2023-02-21
 */
@RestController
@RequestMapping("/module/copy")
public class BizCopyController extends BaseController
{
    @Autowired
    private IBizCopyService bizCopyService;

    /**
     * 查询审批抄送管理列表
     */
    @PreAuthorize("@ss.hasPermi('module:copy:list')")
    @GetMapping("/list")
    public TableDataInfo list(BizCopy bizCopy)
    {
        // startPage();
        List<BizCopy> list = bizCopyService.selectBizCopyList(bizCopy);
        return getDataTable(list);
    }

    /**
     * 导出审批抄送管理列表
     */
    @PreAuthorize("@ss.hasPermi('module:copy:export')")
    @Log(title = "审批抄送管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, BizCopy bizCopy)
    {
        List<BizCopy> list = bizCopyService.selectBizCopyList(bizCopy);
        ExcelUtil<BizCopy> util = new ExcelUtil<BizCopy>(BizCopy.class);
        util.exportExcel(response, list, "审批抄送管理数据");
    }


//    /**
//     * 功能：驼峰命名转下划线命名
//     * 小写和大写紧挨一起的地方,加上分隔符,然后全部转小写
//     */
//    public static String camel2under(String c)
//    {
//        String separator = "_";
//        c = c.replaceAll("([a-z])([A-Z])", "$1"+separator+"$2").toLowerCase();
//        return c;
//    }


    /**
     * 自定义字段导出抄送管理列表
     */
    @PreAuthorize("@ss.hasPermi('module:copy:export2')")
    @Log(title = "审批抄送管理")
    @GetMapping("/get/export2")
    public void export2(HttpServletResponse response, BizCopy bizCopy) throws IllegalAccessException,IOException{

        List<BizCopy> list = bizCopyService.selectBizCopyList(bizCopy);

        //创建HSSFWorkbook（excel文档对象）
        HSSFWorkbook wb = new HSSFWorkbook();
        //创建sheet对象（excel表单）
        HSSFSheet sheet = wb.createSheet("审批抄送管理");

        //字符串分割，并把String[]转换为list
//        String[] fieldsNames = bizCopy.getFieldsNames().split(",");
//        List<String> requestFields = Arrays.stream(fieldsNames).collect(Collectors.toList()) ;
        List<String> requestFields = StrUtil.split(bizCopy.getFieldsNames(),",");

        int startRow = 0;
        //表头
        HSSFRow rowHeader = sheet.createRow(startRow);
        Field[] fields = list.get(0).getClass().getDeclaredFields();
        for (int k = 0;k<requestFields.size();k++){
            String str = requestFields.get(k);
            Field field = Arrays.stream(fields).filter(x-> StrUtil.equals(x.getName(),str,true)).findFirst().get();
            HSSFCell cell3 = rowHeader.createCell(k);
            if(field.getAnnotation(Excel.class) != null){
            cell3.setCellValue(field.getAnnotation(Excel.class).name());
            }
        }
        for(BizCopy bizCopy1:list){
            startRow = startRow +1;
            //表内容
            HSSFRow rowContent = sheet.createRow(startRow);
            for(int k = 0;k<requestFields.size();k++){
                String str = requestFields.get(k);
                Field field = Arrays.stream(fields).filter(x-> StrUtil.equals(x.getName(),str,true)).findFirst().get();
                HSSFCell cell3 = rowContent.createCell(k);
                field.setAccessible(true);
                if(field.get(bizCopy1)!=null){
                cell3.setCellValue(field.get(bizCopy1).toString());
                }
            }
        }
        String fileName = "审批抄送管理";
        //输出excel文件
        OutputStream output = response.getOutputStream();
        //设置Header和contentType,避免报错
        response.addHeader("Content-Disposition","attachment;filename=" + URLEncoder.encode(fileName,"utf-8"));
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
        wb.write(output);
        output.close();
    }

    /**
     * 获取审批抄送管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('module:copy:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(bizCopyService.selectBizCopyById(id));
    }

    /**
     * 新增审批抄送管理
     */
    @PreAuthorize("@ss.hasPermi('module:copy:add')")
    @Log(title = "审批抄送管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody BizCopy bizCopy)
    {
        return toAjax(bizCopyService.insertBizCopy(bizCopy));
    }

    /**
     * 修改审批抄送管理
     */
    @PreAuthorize("@ss.hasPermi('module:copy:edit')")
    @Log(title = "审批抄送管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody BizCopy bizCopy)
    {
        return toAjax(bizCopyService.updateBizCopy(bizCopy));
    }

    /**
     * 修改审批抄送管理
     */
    @PreAuthorize("@ss.hasPermi('module:copy:edit')")
    @Log(title = "审批抄送管理", businessType = BusinessType.UPDATE)
    @PostMapping(value = "/update")
    public AjaxResult editStatusBySerialNum(@RequestBody BizCopy bizCopy)
    {
        return bizCopyService.updateBizCopyBySerialNum(bizCopy);
    }

    /**
     * 删除审批抄送管理
     */
    @PreAuthorize("@ss.hasPermi('module:copy:remove')")
    @Log(title = "审批抄送管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(bizCopyService.deleteBizCopyByIds(ids));
    }

//    /**
//     * 导出审批抄送管理列表
//     */
//    @PreAuthorize("@ss.hasPermi('module:copy:export')")
//    @Log(title = "审批抄送管理", businessType = BusinessType.EXPORT)
//    @PostMapping("/export")
//    public void customExport(BizCopy bizCopy)
//    {
//        List<BizCopy> list = bizCopyService.selectBizCopyList(bizCopy);
//
//        if (StringUtils.isNoneBlank(bizCopy.getFieldsNames())){
//            //字符串分割，并把String[]转换为list，（抄送人id）
//            String[] fieldsNames = bizCopy.getFieldsNames().split(",");
//            List<String> fieldsNameList = Arrays.stream(fieldsNames).collect(Collectors.toList()) ;
//
//            // 需要导出字段的名称，放入map的key中即可
//            Map<String, Object> fieldsName = new HashMap<>();
//
//            fieldsNameList.forEach(name->{
//                fieldsName.put(name, null);
//            });
////
////            ExcelUtil<BizCopy> util = new ExcelUtil<BizCopy>(BizCopy.class);
////            util.exportExcel(response, list, "审批抄送管理数据");
//            CustomExcelUtil<BizCopy> util = new CustomExcelUtil<>(BizCopy.class);
//            // 将fieldsName放入方法中
//            util.exportExcel(list, fieldsName,"审批抄送管理");
//        }
//    }
//
//    /**
//     * 导出抄送（自定义字段）
//     */
//    @Log(title = "审批抄送管理", businessType = BusinessType.EXPORT)
//    @PostMapping("/exportExcel")
//    public void export2(HttpServletResponse response, String column) {
//        try {
//            exportExcel(response, column);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }
//
//    private void exportExcel(HttpServletResponse response, String column) throws IOException {
//        BizCopy bizCopy = new BizCopy();
//        List<BizCopy> list = bizCopyService.selectBizCopyList(bizCopy);
//
//        //前端传入的需要导出的列
//        Set<String> columns = new HashSet<String>(Arrays.asList(column.split(",")));
//        // 测试用
//        //这里需要指定用哪个class去写，然后写到第一个sheet，名字为模板
////        EasyExcel.write("D:\\excel"+System.currentTimeMillis()+".xlsx", BizCopy.class)
////                .includeColumnFiledNames(columns).sheet("模板")
////                .doWrite(list);
//
//        // 前后端导出
//        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
//        response.setCharacterEncoding("UTF-8");
//        // 这里URLEncoder.encode可以防止中文乱码
//        String fileName = URLEncoder.encode("ExcelName", "UTF-8").replaceAll("\\+", "%20");
//        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
//        response.setHeader("fileName",  fileName + ".xlsx");
//
//        EasyExcel.write(response.getOutputStream(), BizCopy.class)
//                .includeColumnFiledNames(columns).sheet("模板")
//                .doWrite(list);
//    }

}
